/* Macro Purpose: Creates a downsampled stack of images from images in a dir
 *                (passed in as an arg) that match a certain img type and also
 *                match a 'base name' (in this case start with the base).
 *                It does this by opening each img, downsampling them,
 *                and then saving them all as a zip'd stack.
 *                
 * Parameters (as one str): 1:Debug (boolean indicating if this macro should print status, etc)
 *                          2:Path of images dir.  3:Path to result dir  4:Result img name
 *                          5:Scale to downsample by (2 means downsample to 1/2 orig dimensions)
 *                          6:Filename to open "base name". Like "proj" in "proj1259.fits"
 *                          7:The starting such image number to open (i.e., #10 in a dir with 100 images)
 *                          8:The max number of such images to open.
 *                          9:file extension of the stack (e.g., 'ZIP')
 */

argsStr = getArgument();  // try to get arg passed in by user
if(argsStr == "") {
	print("\nNo argument string passed to this Fiji macro. Exiting now.\n");
	exit;
}
debugIt = false;
// Print str if in Debug mode
function printD(str) { 
  if(debugIt) print(str);	
} // end function printD() /////
//////////////////////////////////////////////////////////////////////////////
/// CONSTANTS & PARAMS (most get overridden by passed-in vals) /////////////// 
arg_delimeter = "@"; // the delimeter used to seperate args in the single arg str passed in

file_extension_to_open = ".fits";

saveImgPath = "/home/jfrank3/www-home/imagerecon/Images/";
saveImgName = "stack_from_resampled_FITS.zip";
saveImgType = "ZIP";

scale = 4;  // the ratio to downsample by (scale=4 means resample to 1/4 size)
shouldBrighten = true;
//// end Constants & Params //////////////////////
//////////////////////////////////////////////////

argsArray = split(argsStr, arg_delimeter); // split str on delimeter
// Break out the appropriate params from the argArray
debugIt     = argsArray[0];
pathToImg   = argsArray[1];
saveImgPath = argsArray[2];
saveImgName = argsArray[3];
scale       = argsArray[4];
imgBaseName = argsArray[5];
startImgNum = argsArray[6];  // sometimes Gregor wants to be able to start the stack from the middle of the imgs
maxImgCount = argsArray[7];
saveImgType = argsArray[8];

// Get a list of all files in dir
//filesInSourceDir = getFileList(pathToImg);
filesInSourceDir = getFileList(pathToImg);

///// DEBUGGING STATEMENT ////
printD("\nYou passed into this macro args: "); 
for(i=0; i < argsArray.length; i++) {
	printD("\"" + argsArray[i] + "\"");
}


// Get a count of approp images so we can allocate array to hold them
// (there might even be enough such images to meet the maxImgCount)
for( i = 0, appropImgCount = 0; i < filesInSourceDir.length; i++ ) {
	if(endsWith(filesInSourceDir[i], file_extension_to_open) && 
	   startsWith(filesInSourceDir[i], imgBaseName)) {

			//imagesToOpen[appropImgCount] = filesInSourceDir[i];
			appropImgCount++;
	}
}

// Now get a list of approp images
cappedNumImages = minOf(appropImgCount, maxImgCount);
imagesToOpen = newArray(cappedNumImages);
// Makes sure the file has the appropriate filename type and that the stack starts with the caller's desired starting img num
// Also, stop filling the stack array once we meet the quota 
for( i = 0, appropImgCount = 0, stackImgCount = 0; i < filesInSourceDir.length && stackImgCount != cappedNumImages; i++ ) {
	if(endsWith(filesInSourceDir[i], file_extension_to_open) && 
	   startsWith(filesInSourceDir[i], imgBaseName )) {

			appropImgCount++; // we found an image with appropriate filename type
			if(appropImgCount >= startImgNum) { // if the appropriate filename count has met the caller's desired starting img
				imagesToOpen[stackImgCount] = filesInSourceDir[i];
				stackImgCount++;
			}
	}
}



// Open imgs
for( i = 0; i < cappedNumImages; i++ ) {
	open(pathToImg + "/" + imagesToOpen[i]);
}
// Brighten images so resultant stack will be legible - can't get this to work in Headless mode!
/*if(shouldBrighten) {
	for( i = 0; i < filesInSourceDir.length; i++ ) {
		if(endsWith(filesInSourceDir[i], file_extension_to_open)) {
			selectWindow(filesInSourceDir[i]);
			//run("Brightness/Contrast...");
			//setMinAndMax(1150, 3650);
			//call("ij.ImagePlus.setDefault16bitRange", 0);
			//run("Enhance Contrast", "saturated=0.35");
			//run("Enhance Contrast", "saturated=0.4 normalize");
		}
	}
}*/


// Downsample imgs (in prep of sending the stack to the client for previewing)
for( i = 0; i < cappedNumImages; i++ ) {

		selectWindow(imagesToOpen[i]);
		// If the images are "slice[int].fits" type, they are probably 32-bit, which will not resample in Fiji,
		// so we must set their type to 16-bit. This assumption will need more testing
		if(imgBaseName == "slice"){
			run("16-bit");
		}
		
		run("Resample", "factor=" + scale + " factor=" + scale + " factor=" + scale);
		// Brighten images AGAIN (since downsampling darkens them) so resultant stack will be legible
		//run("Enhance Contrast", "saturated=0.35");		//run("Enhance Contrast", "saturated=0.4 normalize"); // doesn't work
}

// Create the stack from all open images - first close the orig (full-sized) img windows so we don't stack them
for( i = 0; i < cappedNumImages; i++ ) {
		selectWindow(imagesToOpen[i]);
		close();
}
// Make the stack (# of open images must be at least 2 for Fiji to cooperate)
if(cappedNumImages > 1) {
	run("Images to Stack", "name=[] title=[] use keep");
}

//run("Next Slice [>]");
//run("Enhance Contrast", "saturated=0.4 normalize");

saveAs(saveImgType, saveImgPath + "/" + saveImgName);

printD("Macro finished saving resampled stack to: \"" + saveImgPath + saveImgName + "\"");
